package com.qfedu.openplateform.gateway.filter;

import com.alibaba.fastjson.JSON;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.qfedu.openplateform.cache.service.CacheService;
import com.qfedu.openplateform.common.constans.ExceptionDict;
import com.qfedu.openplateform.common.entity.ResponseData;
import com.qfedu.openplateform.gateway.config.ApplicationHolder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;


/**
 * 幂等 校验该请求是否处理过
 * 利用签名 验证
 *
 *  1.获取签名
 *  2.使用 redis  setnx  如果对应的签名不存在 返回 true  ---->放行
 *                      如果对应的签名存在 返回 false  ---->拦截  拒绝重复请求
 *
 *
 */

public class IdempotentFilter implements HandlerInterceptor {
    @Autowired
    private CacheService cacheService = ApplicationHolder.getApplicationContext().getBean(CacheService.class);

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        // 前端提交签名 比对  手动传
        String sign = request.getParameter("sign");

        //String s = cacheService.getFromRedis(sign);
        //将
        if (cacheService.setNx(sign+request.getRequestURL(), "jwt12", 3600)) {
            return true;
        }
        response.setContentType("application/json;charset=utf-8");
        ResponseData bean = new ResponseData();
        bean.setCode(ExceptionDict.LIMIT_ERROR);
        bean.setMessage("不能重复请求");
        try {
            response.getWriter().println(JSON.toJSONString(bean));
        } catch (JsonProcessingException ex) {
            ex.printStackTrace();
        }
        return false;
    }


}
